<template>
  <div class="material-container">
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="材质名称">
          <el-input v-model="queryParams.name" placeholder="请输入材质名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增材质</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-container">
      <el-table :data="materialList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="材质名称" width="150"></el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
        <el-table-column label="材质图" width="120">
          <template #default="scope">
            <el-image 
              style="width: 80px; height: 80px" 
              :src="scope.row.imageUrl" 
              fit="cover"
              :preview-src-list="[scope.row.imageUrl]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格(元/米)" width="120">
          <template #default="scope">
            {{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.status === 1">
              删除
            </el-button>
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="(val) => handleStatusChange(scope.row, val)"
              active-text="启用"
              inactive-text="禁用">
            </el-switch>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="queryParams.pageSize"
          :current-page="queryParams.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加或修改材质对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="600px"
      :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="materialFormRef" label-width="100px">
        <el-form-item label="材质名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入材质名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入描述"
            :rows="3">
          </el-input>
        </el-form-item>
        <el-form-item label="价格(元/米)" prop="price">
          <el-input-number 
            v-model="form.price" 
            :precision="2" 
            :step="10" 
            :min="0"
            style="width: 180px;">
          </el-input-number>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number 
            v-model="form.stock" 
            :min="0" 
            :step="10" 
            style="width: 180px;">
          </el-input-number>
        </el-form-item>
        <el-form-item label="材质图" prop="image">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :data="{
              module: 'material',
              relationId: form.id || 0
            }">
            <img v-if="form.image" :src="form.image" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="材质特性">
          <el-checkbox-group v-model="form.features">
            <el-checkbox label="透气性好">透气性好</el-checkbox>
            <el-checkbox label="保暖">保暖</el-checkbox>
            <el-checkbox label="防水">防水</el-checkbox>
            <el-checkbox label="弹性好">弹性好</el-checkbox>
            <el-checkbox label="易打理">易打理</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  status: '',
})

// 表格数据
const materialList = ref([])
const total = ref(0)
const loading = ref(false)

// 表单对话框
const dialog = reactive({
  title: '',
  visible: false,
})

// 表单数据
const materialFormRef = ref(null)
const form = reactive({
  id: undefined,
  name: '',
  description: '',
  price: 0,
  stock: 0,
  image: '',
  features: [],
  status: 1,
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入材质名称', trigger: 'blur' },
    { min: 2, max: 50, message: '材质名称长度在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '描述长度不能超过500个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传材质图', trigger: 'change' }
  ]
}

// 获取材质列表
const getMaterialList = () => {
  loading.value = true
  
  // 构建查询参数
  const params = new URLSearchParams();
  params.append('pageNum', queryParams.pageNum);
  params.append('pageSize', queryParams.pageSize);
  if (queryParams.name) params.append('name', queryParams.name);
  if (queryParams.status !== '') params.append('status', queryParams.status);
  
  // 调用后端API获取数据
  fetch(`/api/clothing/material/list?${params.toString()}`)
    .then(response => response.json())
    .then(res => {
      console.log('获取材质列表响应:', res);
      if (res && res.data) {
        materialList.value = res.data.records || [];
        total.value = res.data.total || 0;
      } else {
        ElMessage.error('获取数据失败: ' + (res.message || '未知错误'));
        materialList.value = [];
        total.value = 0;
      }
    })
    .catch(error => {
      console.error('获取数据失败:', error);
      ElMessage.error('获取数据失败，请稍后重试');
      materialList.value = [];
      total.value = 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getMaterialList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.status = ''
  handleQuery()
}

// 分页大小改变
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getMaterialList()
}

// 分页页码改变
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getMaterialList()
}

// 新增材质
const handleAdd = () => {
  dialog.title = '添加材质'
  dialog.visible = true
  Object.keys(form).forEach(key => {
    if (key === 'price' || key === 'stock') {
      form[key] = 0
    } else if (key === 'features') {
      form[key] = []
    } else if (key === 'status') {
      form[key] = 1
    } else {
      form[key] = ''
    }
  })
  form.id = undefined
  
  // 表单清除验证
  if (materialFormRef.value) {
    materialFormRef.value.resetFields()
  }
}

// 编辑材质
const handleEdit = (row) => {
  dialog.title = '编辑材质'
  dialog.visible = true
  Object.assign(form, {
    id: row.id,
    name: row.name,
    description: row.description,
    price: row.price,
    stock: row.stock,
    image: row.imageUrl,
    features: row.features || [],
    status: row.status
  })
  
  // 下一次DOM更新后重置表单验证
  setTimeout(() => {
    if (materialFormRef.value) {
      materialFormRef.value.clearValidate()
    }
  }, 0)
}

// 提交表单
const submitForm = () => {
  materialFormRef.value.validate((valid) => {
    if (valid) {
      const method = form.id ? 'PUT' : 'POST'
      const apiUrl = '/api/clothing/material'
      
      // 处理表单数据
      const formData = {
        ...form,
        // 确保只包含需要的字段
        name: form.name,
        description: form.description,
        price: form.price,
        stock: form.stock,
        imageUrl: form.image,
        features: form.features,
        status: form.status
      }
      
      // 如果是编辑模式，确保包含ID
      if (form.id) {
        formData.id = form.id
      }
      
      fetch(apiUrl, {
        method: method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        body: JSON.stringify(formData)
      })
        .then(response => response.json())
        .then(res => {
          if (res && res.code === 0) {
            ElMessage.success(form.id ? '更新成功' : '添加成功')
            dialog.visible = false
            getMaterialList()
          } else {
            ElMessage.error((form.id ? '更新' : '添加') + '失败: ' + (res.message || '未知错误'))
          }
        })
        .catch(error => {
          console.error((form.id ? '更新' : '添加') + '失败:', error)
          ElMessage.error((form.id ? '更新' : '添加') + '失败，请稍后重试')
        })
    }
  })
}

// 删除材质
const handleDelete = (row) => {
  // 先检查状态
  if (row.status === 1) {
    ElMessage.warning('启用状态的材质不能删除，请先禁用');
    return;
  }

  ElMessageBox.confirm('确认要删除该材质吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用删除API
    fetch(`/api/clothing/material/${row.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    })
      .then(response => response.json())
      .then(res => {
        console.log('删除材质响应:', res);
        if (res && res.code === 0) {
          ElMessage.success('删除成功');
          getMaterialList();
        } else {
          ElMessage.error('删除失败: ' + (res.message || '未知错误'));
        }
      })
      .catch(error => {
        console.error('删除失败:', error);
        ElMessage.error('删除失败，请稍后重试');
      });
  }).catch(() => {
    // 取消删除，不做任何操作
  });
}

// 状态改变
const handleStatusChange = (row, status) => {
  const text = status === 1 ? '启用' : '禁用';
  
  fetch(`/api/clothing/material/status?id=${row.id}&status=${status}`, {
    method: 'PUT',
    headers: {
      'Authorization': 'Bearer ' + localStorage.getItem('token')
    }
  })
    .then(response => response.json())
    .then(res => {
      console.log('更新状态响应:', res);
      if (res && res.code === 0) {
        row.status = status;
        ElMessage.success(`已${text}`);
      } else {
        ElMessage.error(text + '失败: ' + (res.message || '未知错误'));
      }
    })
    .catch(error => {
      console.error(text + '失败:', error);
      ElMessage.error(text + '失败，请稍后重试');
    });
}

// 材质图上传成功
const handleImageSuccess = (res) => {
  console.log('材质图上传成功，响应:', res);
  if (res && res.data) {
    form.image = res.data;
    ElMessage.success('材质图上传成功');
  } else {
    ElMessage.error('材质图上传失败: ' + (res.message || '未知错误'));
  }
}

// 材质图上传前检查
const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('只能上传JPG或PNG格式的图片!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!');
    return false;
  }
  return true;
}

onMounted(() => {
  getMaterialList()
})
</script>

<style scoped>
.material-container {
  padding: 20px;
}
.filter-container, .table-container {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
</style> 